Skip to content

fix(rag): restore bounded live retrieval reranking#919

Merged
BigSimmo merged 5 commits into
mainfrom
codex/bounded-release-rerank
Jul 19, 2026
Merged

fix(rag): restore bounded live retrieval reranking#919
BigSimmo merged 5 commits into
mainfrom
codex/bounded-release-rerank

Conversation

@BigSimmo

@BigSimmo BigSimmo commented Jul 19, 2026

Copy link
Copy Markdown
Owner

Final release verification

  • Required hosted CI passed on exact PR head 4f10137551b8e09d724b87219852e03317cf50b9: static checks, unit coverage, production build, safety/config, Semgrep, Gitleaks, GitGuardian, and PR policy.
  • Repository automation merged the PR as 313e57a405da53dfcb0d851a937af2f50465a489.
  • Exact-main live canary passed: https://github.com/BigSimmo/Database/actions/runs/29681465785
    • Retrieval: 36/36; document recall@5 1.0; content recall@5 1.0; MRR@10 0.8505; content MRR@10 0.9159; nDCG@10 0.917; irrelevant-source rate@10 0.1083; required-signal coverage@10 1.0; zero failed/latency-failed cases.
    • Live answer subset: 8/8; grounded-supported rate 1.0; expected-source hit rate 1.0; citation failure rate 0; numeric-grounding failure rate 0; danger failure rate 0; zero route-ceiling failures.
  • Supabase project Clinical KB Database (sjrfecxgysukkwxsowpy) was rechecked through MCP after deployment and is ACTIVE_HEALTHY; the intended migration ledger entries are present and both edge functions are active.

Summary

  • Restore the last-live-green bounded second-stage score as a separate release-order signal while preserving raw hybrid coverage scores and the newer unbounded app-layer rank score.
  • Sort distinct released chunks by raw hybrid or the bounded second-stage score, retain the strongest released-hybrid copy of duplicate chunks, and keep finalRank aligned with the returned order.
  • Add focused regression coverage proving unbounded rank magnitude cannot replace the bounded release order.

Verification

  • npm run verify:pr-local
  • npm run verify:ui when UI, routing, styling, browser behavior, reduced-motion, or forced-colors behavior changed (full Chromium gate passed earlier in this release task: 239/239; this corrective diff is backend-only)
  • npm run verify:release before release or handoff confidence claims
  • npm run eval:retrieval:quality (must stay 36/36) when retrieval, ranking, selection, chunking, or scoring behavior changed — draft is intentionally blocked pending the exact-head hosted canary
  • npm run eval:rag -- --limit 15 + npm run eval:quality -- --rag-only when answer generation, the synthesis prompt, or answer post-processing changed (not applicable: no answer-generation change; the hosted canary answer subset remains required)
  • npm run check:production-readiness when clinical workflow, privacy, environment, Supabase, source governance, or deployment behavior changed (passed earlier in this release task)
  • npm run check:deployment-readiness when deployment startup, hosting, or rollout behavior changed (not applicable: no hosting/startup change)

Focused checks:

  • npm run test -- tests/rag-answer-fallback.test.ts tests/answer-ranking.test.ts tests/rag-second-stage-ranking.test.ts tests/retrieval-selection.test.ts tests/semantic-rerank.test.ts — 5 files, 85 tests passed
  • npm run typecheck — passed
  • npx prettier --check src/lib/rag.ts src/lib/types.ts tests/rag-second-stage-ranking.test.ts — passed
  • git diff --check — passed
  • npm run verify:cheap — attempted but deferred because another legitimate Database worktree held the repository-wide heavyweight lock for its Chromium UI gate

Live regression evidence motivating this correction:

Risk and rollout

  • Risk: Medium. This intentionally changes the final ordering of search results back to the bounded release signal proven by the last-green live corpus run; raw hybrid confidence and unbounded answer-evidence ranking remain available separately.
  • Rollback: Revert this commit to restore the current main behavior.
  • Provider or production effects: The explicitly authorized hosted canary will read the live Clinical KB corpus and call configured OpenAI evaluation services. This PR does not mutate production data or deploy application infrastructure.

Clinical Governance Preflight

  • Source-backed claims still require linked source verification before clinical use
  • No patient-identifiable document workflow was introduced or expanded without explicit governance approval
  • Supabase target remains Clinical KB Database (sjrfecxgysukkwxsowpy)
  • Service-role keys and private document access remain server-only
  • Demo/synthetic content remains clearly separated from real clinical sources
  • Source metadata, review status, and outdated/unknown-source behavior remain conservative
  • Deployment classification/TGA SaMD impact was checked when clinical decision-support behavior changed

Notes

  • Required hosted CI and the exact-main live retrieval plus answer-quality canary are green; the repository auto-merged this PR after its required checks passed.

Summary by CodeRabbit

  • New Features
    • Medication monitoring searches now normalize to canonical medication subject tokens and better anchor results to the requested medication and clinical subject.
    • Second-stage reranking now surfaces a released-order score in ranking explanations to improve final released ordering.
  • Bug Fixes
    • Retrieval evidence selection for monitoring queries now requires explicit clinical-subject matching, with clear “retrieval required” signal reasoning.
    • Released ordering is more stable and bounded for reranked results, including duplicate and mismatched-subject cases.
  • Tests
    • Added and expanded coverage for medication monitoring subject anchoring and second-stage stabilization/release ordering behavior.

@supabase

supabase Bot commented Jul 19, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project sjrfecxgysukkwxsowpy because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 30e8d6f4-e43c-4996-82ed-1dede29d8337

📥 Commits

Reviewing files that changed from the base of the PR and between 72bca3a and 4f10137.

📒 Files selected for processing (1)
  • tests/rag-second-stage-ranking.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/rag-second-stage-ranking.test.ts

📝 Walkthrough

Walkthrough

Medication monitoring queries now require subject-specific retrieval evidence. Second-stage reranking persists a bounded releaseRankScore, and released-result stabilization uses it for deduplication, ordering, and telemetry.

Changes

Medication retrieval and ranking

Layer / File(s) Summary
Medication monitoring subject selection
src/lib/clinical-search.ts, src/lib/retrieval-selection.ts, tests/clinical-search.test.ts, tests/retrieval-selection.test.ts
Monitoring queries derive medication subject tokens, require matching clinical_subject evidence, and annotate selected results with the required signal.
Second-stage release ranking and stabilization
src/lib/types.ts, src/lib/rag.ts, tests/rag-second-stage-ranking.test.ts
Reranking persists bounded releaseRankScore values, and released-result stabilization uses them for duplicate selection, ordering, final ranks, and telemetry.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Query
  participant RetrievalIntent
  participant EvidenceSelection
  participant Reranker
  participant ReleasedOrdering
  Query->>RetrievalIntent: classify medication monitoring query
  RetrievalIntent->>EvidenceSelection: require clinical_subject
  EvidenceSelection-->>Reranker: annotate subject match
  Reranker->>Reranker: compute bounded releaseRankScore
  Reranker->>ReleasedOrdering: persist score for final ordering
  ReleasedOrdering-->>Query: deduplicated ranked results
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: restoring bounded live retrieval reranking.
Description check ✅ Passed The description follows the template and covers summary, verification, risk, governance, and notes with relevant details.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/bounded-release-rerank

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 19, 2026

Copy link
Copy Markdown

CI triage

CI failed on this PR. Automated classification of the 2 failed job(s):

  • Static PR checksneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • PR requiredneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.

Compared with main CI run #3542 (success).

Classification is evidence routing, not permission to ignore a failure. Exact quarantined Playwright identities remain governed by the flake ledger.

@BigSimmo
BigSimmo marked this pull request as ready for review July 19, 2026 09:05
@BigSimmo
BigSimmo enabled auto-merge (squash) July 19, 2026 09:06

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8a99227447

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/rag.ts Outdated
@BigSimmo

Copy link
Copy Markdown
Owner Author

@codex resolve actionable Codex review findings for this pull request and current head using the repository instructions. This is the pull request's single automatic repair pass: do not perform a fresh review, create new standalone findings, or request another review. Work only the existing unresolved Codex threads on the current head. Always fix P0 and P1 findings. For P2 and lower findings, fix only clear, scoped, low-risk issues; otherwise disposition them with a concise reason. After fixing or dispositioning a thread, reply in that thread with as the first line, followed by a concise summary; that marker authorizes the workflow to close that exact thread. If human input or new authorization is required, do not use the marker and leave the thread open with the blocker. Finish only after every actionable thread is fixed or dispositioned and closed, or explicitly left open for a human decision. Do not update the branch from main, address unrelated reviews, broaden scope, or create more than one scoped fix commit. Do not use external APIs, paid services, credentials, dependency changes, or broad refactors unless explicitly authorized. Add targeted tests where behavior changes and run the narrowest relevant validation.

Comment thread src/lib/rag.ts Outdated
Key stabilizeReleasedSearchOrder off whether the final result set carries
releaseRankScore instead of the sticky second_stage_rerank_used telemetry
flag. Sync telemetry to the final set so intermediate rerank passes cannot
mis-route later hybrid fallthrough results.

Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7cf8e55633

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/rag.ts Outdated
Comment thread src/lib/rag.ts
@BigSimmo
BigSimmo merged commit 313e57a into main Jul 19, 2026
28 checks passed
@BigSimmo
BigSimmo deleted the codex/bounded-release-rerank branch July 19, 2026 09:20

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4f10137551

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/rag.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants